package com.tanhua.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVO;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.template.OssTemplate;
import com.tanhua.util.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



@Service
public class VideoService {
    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private PublishApi publishApi;
    @Autowired
    private FastFileStorageClient fastClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发布视频
     * @param videoFile
     * @param videoThumbnail
     * @return
     */
    public ResponseEntity upload(MultipartFile videoFile, MultipartFile videoThumbnail) throws IOException {
        User user = UserHolder.getUser();
        //上传视频
        String filename = videoFile.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = fastClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
        //上传封面
        String picUrl = ossTemplate.upHeaderPhoto(videoThumbnail.getInputStream(), videoThumbnail.getOriginalFilename());
        Video video = new Video();
        video.setUserId(user.getId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        //保存信息
        String videoId = videoApi.save(video);
        //发送消息
        rocketMQTemplate.convertAndSend(videoId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity videoList(Integer page, Integer pagesize) {
        User user = UserHolder.getUser();
        PageResult pageResult = videoApi.videoList(page,pagesize);
        List<Video> items = pageResult.getItems();
        ArrayList<VideoVO> vos = new ArrayList<>();
        for (Video video : items) {
            //
            UserInfo userInfo = userInfoApi.findUserInfo(video.getUserId());
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(userInfo,videoVO);
            videoVO.setUserId(userInfo.getId());
            //
            BeanUtils.copyProperties(video,videoVO);
            videoVO.setId(video.getId().toHexString());
            videoVO.setCover(video.getPicUrl());
            videoVO.setSignature("12345");
            Boolean hasKey = redisTemplate.hasKey("userId" + user.getId() + "focus" + video.getUserId());
            videoVO.setHasFocus(hasKey?1:0);

            videoVO.setHasLiked(0);
            vos.add(videoVO);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity like(String videoId) {
        User user = UserHolder.getUser();
        Comment comment = new Comment();
        comment.setPubType(2);
        comment.setUserId(user.getId());
        comment.setCommentType(1);
        comment.setPublishId(new ObjectId(videoId));
        Publish publish = publishApi.findById(videoId);
        comment.setPublishUserId(publish.getUserId());
        int likeCount = commentApi.save(comment);
        redisTemplate.opsForValue().set("userId"+user.getId()+"like"+videoId,"22");
        //发送消息
        rocketMQTemplate.convertAndSend(videoId);
        return ResponseEntity.ok(likeCount);
    }

    public ResponseEntity focus(Long uid) {
        User user = UserHolder.getUser();
        videoApi.focus(user.getId(),uid);
        redisTemplate.opsForValue().set("userId"+user.getId()+"focus"+uid,"22");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity unFocus(Long uid) {
        User user = UserHolder.getUser();
        videoApi.unFocus(user.getId(),uid);
        redisTemplate.delete("userId"+user.getId()+"focus"+uid);
        return ResponseEntity.ok(null);

    }

    public ResponseEntity dislike(String videoId) {

        User user = UserHolder.getUser();
        Comment comment = new Comment();
        comment.setPubType(2);
        comment.setPublishId(new ObjectId(videoId));
        comment.setCommentType(1);
        comment.setUserId(user.getId());
        int likeCount = commentApi.remove(comment);
        redisTemplate.delete("userId"+user.getId()+"like"+videoId);
        //发送消息
        rocketMQTemplate.convertAndSend(videoId);
        return ResponseEntity.ok(likeCount);
    }
}
